
// 

/* --- trigger conditions ---

@greater(triggerOutputs()?['body/ID'], 81)
@equals(triggerOutputs()?['body/FlowStatus'], 'Submit')

--- trigger conditions --- */


// 表服务
var List_ContractList = {}
var List_ApprovalData = {}
var List_Approver = {}
var List_Department = {}
var List_OtherServicesDepartment = {}


// 当前表单内容
var triggerOutputs = {}

// 获取当前合同项
var Get_item = List_ContractList.getItem(triggerOutputs['Id'])

// 更新流程状态
List_ContractList.update(triggerOutputs['Id'], 
    {
    'Flow Status':'In Progress',
    'Runflow': null
    })


// 当前审批轮数
var Round = triggerOutputs.ApprovalBatch
// 实际来自部门表的Title
var 品牌 = triggerOutputs['Maison Value'] // Department/Value
var 需审批的部门 =[]
var 已审批的部门 = []
var ApprovealUser = []
var ApproverUserEmail = [] // 第一批审批人
var AllApprover = []
var Contract_Type = triggerOutputs['Contract Type Value'] // Value
var 申请人Claims = triggerOutputs['Applicant/Claims']
var DepartmentHead =''
var tableDepartment = []
var 当前审批节点 = ''

// 通过当前合同Id查询已生成的审批节点
var Get_items_3 =  List_ApprovalData.getItems(`ContractId eq ${triggerOutputs['body/ID']}`)

// 如果是第一次提交
if(Get_items_3.length == 0)
{   
    // 查询Approver表，获取所有审批人信息
    var Get_Approver = List_Approver.getItems()

    // 通过当前品牌字段查询关联的部门信息（这里应该是通过Title来查询）
    var Get_items = List_Department.getItems(`MaisonCode eq '${品牌}'`) // Bug

    // 查询Other Service Department信息
    var Get_items_OtherServicesDepartment = List_OtherServicesDepartment.getItems(`MaisonCode eq '${品牌}'`)

    // 合同类型为Service、Leasing或Other
    if(Contract_Type == "Service"
        || Contract_Type == "Other scenarios for company chop"
        || Contract_Type == "Leasing")
    {
        // START ------ 获取所有需要审批的部门 ------

        // 额外勾选的审批部门
        var otherDepartment = triggerOutputs['OtherDepartments']
        需审批的部门 = otherDepartment

        // 涉及法务 写入Legal -Legal Backup
        if(triggerOutputs['LegalInvolved'] == true)
        {
            需审批的部门.append('Legal')
        }

        // 涉及财务 写入三组Finance以及财务CFO
        if(triggerOutputs['LegalInvolved'] == true) // Bug
        {
            // 追加 写入Finance Tax
            需审批的部门.append('Finance Tax')

            // Boutique/Office Type Value
            if(triggerOutputs['Boutique/Office Type Value'] != "Office")
            {
                // 追加 写入Finance AP 2
                需审批的部门.append('Finance RBO')
            }

            // 追加 写入Finance AP
            需审批的部门.append('Finance AP')

            // 追加 写入财务CFO
            需审批的部门.append('CFO Office')
        }

        // 追加 写入部门经理
        需审批的部门.append('DepartmentHead')

        // 如果合同金额大于相应值，写入部门经理+1
        if(triggerOutputs()['body/ContractAmount'] > int(Get_items['body/value'][0]['MaxContractAmount'])) // Bug
        {
            // 追加 写入部门经理+1经理
            需审批的部门.append('SeniorDepartmentHead')
        }

        // 追加 写入CEO Office
        需审批的部门.append('CEO Office')

        // 追加 写入CEO
        需审批的部门.append('CEO')

        // END ------ 获取所有需要审批的部门 ------
        

        // 合同类型不同时，设置数组变量为不同值
        if(Contract_Type == "Leasing")
        {
            tableDepartment = Get_items['body/value']
        }
        else
        {
            if(Contract_Type == "Other scenarios for company chop" 
                || Contract_Type == "Service"
            )
            {
                tableDepartment = Get_items_OtherServicesDepartment['body/value']
            }
        }

        // 设置ApprovalUser;生成ApprovalData占位
        foreach(item in 需审批的部门)
        {
            // ----- Start 处理第一批审批人，需发送邮件 -----

            // 当前项为IT;Security;Digital;Procurement;Logistic
            var str = 'IT;Security;Digital;Procurement;Logistic'
            if(str.has(item))
            {
                // 选择-获取当前部门所有审批人的Claims
                var 当前部门所有审批人的Claims = tableDepartment[0][item].select(x => x.Claims)

                foreach(claims in 当前部门所有审批人的Claims)
                {
                    ApprovealUser.append(claims)
                }

                // 选择-获取当前部门所有审批人的Email
                var 当前部门所有审批人的Email = tableDepartment[0][item].select(x => x.Email)
                foreach(email in 当前部门所有审批人的Email)
                {
                    ApproverUserEmail.append(emial)
                }

                // 写入到Approval Data 2
                List_ApprovalData.insert({
                    "item/Title": "@item()",
                    "item/Applicant/Claims": "@variables('申请人Claims')",
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": "@item()",
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": 当前部门所有审批人的Claims,
                    "item/ApprovalNode": "LegalFinance"
                })
            }

            // 当前项为Legal
            if(item == "Legal")
            {
                // 查找角色为 Legal 开头的审批人
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item + ' ' + triggerOutputs['Maison Value']
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                foreach(approval_Clamims in approvals_Claims)
                {
                    ApprovealUser.append(approval_Clamims)
                }

                var approval_Emails = approvals.select(x=> x['Approver']['Email'])

                foreach(approval_Email in approval_Emails)
                {
                    ApproverUserEmail.append(approval_Email)
                }

                // 写入到Approval Data 3
                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": "@item()",
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "LegalFinance"
                })

            }

            // 当前项为Legal Backup-----
            if(item == "Legal Backup") // 费代码？
            {
                // 查找角色为 Legal Backup 开头的审批人
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item + ' ' + triggerOutputs['Maison Value']
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                foreach(approval_Clamims in approvals_Claims)
                {
                    ApprovealUser.append(approval_Clamims)
                }

                var approval_Emails = approvals.select(x=> x['Approver']['Email'])

                foreach(approval_Email in approval_Emails)
                {
                    ApproverUserEmail.append(approval_Email)
                }

                // 写入到Approval Data 3

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "LegalFinance"
                })
            }

            // 当前项为Finance AP-Tax
            var text = "Finance AP\nFinance Tax";
            if(text.has(item))
            {
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                foreach(approval_Clamims in approvals_Claims)
                {
                    ApprovealUser.append(approval_Clamims)
                }

                var approval_Emails = approvals.select(x=> x['Approver']['Email'])

                foreach(approval_Email in approval_Emails)
                {
                    ApproverUserEmail.append(approval_Email)
                }

                // 写入到Approval Data 3

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "LegalFinance"
                })
            }

            // 当前项为Finance RBO
            if(item == "Finance RBO")
            {
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item + ' ' + triggerOutputs['Boutique/Office Type Value']
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                foreach(approval_Clamims in approvals_Claims)
                {
                    ApprovealUser.append(approval_Clamims)
                }

                var approval_Emails = approvals.select(x=> x['Approver']['Email'])

                foreach(approval_Email in approval_Emails)
                {
                    ApproverUserEmail.append(approval_Email)
                }

                // 写入到Approval Data 3

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "LegalFinance"
                })
            }

            // ----- End 处理第一批审批人，需发送邮件 -----


            // ----- Start 处理后续审批人 -----

            // 此处应该放在 SeniorDepartmentHead 下面
            // 当前项为CFO Office
            if(item == "CFO Office")
            {
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "LegalFinance"
                })
            }

            // 当前项为DepartmentHead
            if(item == "DepartmentHead")
            {
                var claims = tableDepartment[0][item][Claims]

                List_ApprovalData.insert({
                    "item/Title": "Department Head",
                    "item/Applicant/Claims": "@variables('申请人Claims')",
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": "Department Head",
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": claims,
                    "item/ApprovalNode": "DepartmentHead"
                })
            }

            // 当前项为SeniorDepartmentHead
            if(item == "SeniorDepartmentHead")
            {
                var claims = tableDepartment[0][item][Claims]

                List_ApprovalData.insert({
                    "item/Title": "Senior Department Head",
                    "item/Applicant/Claims": "@variables('申请人Claims')",
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": "Senior Department Head",
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": claims,
                    "item/ApprovalNode": "SeniorDepartmentHead"
                })
            }

            // 当前项为CEO Office
            if(item == "CEO Office")
            {
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "CEOOffice"
                })
            }

            // 当前项为CEO
            if(item == "CEO")
            {
                var approvals = Get_Approver['body/value'].where(approval => {
                    approval['Role/Value'] == item
                })

                var approvals_Claims = approvals.select(x=> x['Approver']['Claims'])

                List_ApprovalData.insert({
                    "item/Title": item,
                    "item/Applicant/Claims": 申请人Claims,
                    "item/ContractId": "@triggerOutputs()?['body/ID']",
                    "item/Position": item,
                    "item/is_completed": true,
                    "item/is_validate": true,
                    "item/batch_no": 1,
                    "item/is_revoked": false,
                    "item/is_backup": false,
                    "item/AllApprover": approvals_Claims,
                    "item/ApprovalNode": "CEO"
                })
            }

            // ----- End 处理后续审批人 -----
        }
    }

    // 合同类型为Finance Stamp
    if(Contract_Type == "Finance Stamp") //未完善的
    {
        // 获取所有需要审批的部门-Finance Stamp
        需要审批的部门.append("Approver1") // Bug: should be: Approver
        需要审批的部门.append("DepartmentHead")
    }

    // Get items-ApproverData
    var Get_items_ApproverData = List_ApprovalData.getItems(`ContractId eq '${triggerOutputs()['body/ID']}'`)

    // AllApprover
    {   // 感觉是费代码
        var text = "IT\nSecurity\nDigital\nProcurement\nLogistic\nLegal\nFinance AP\nFinance RBO Own\nFinance Tax\n\nFinance RBO Mall"
        var approvals = Get_items_ApproverData['body/value']
            .where(x => text.has(x['Position']))

        foreach(item in approvals)
        {
            var ls_claims = item['AllApprover'].select(x=> x['Claims'])
            foreach(claim in claims)
            {
                AllApprover.append(claim)
            }
        }
    }

    // 设置ApprovalUser和ApprovedUser
    List_ContractList.update(id=triggerOutputs['Id'],
        {
            "item/InvolveMonetary": true,
            "item/LegalInvolved": true,
            "item/ApprovalUser": ApprovealUser,
            "item/ApprovedUser": [],
            "item/ApprovalNode": "LegalFinance",
            "item/SameGroup": []
        }
    )

    foreach(user in ApprovealUser) // Bug 这里没有区分审批阶段，把所有阶段的审批人都发送邮件了
    {
        sendMail(item['Email'])
    }
}
